<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    div {
      width: 500px;
      height: 300px;
    }
  </style>
</head>
<body>
<div></div>
<script>
  var div = document.querySelector('div');
  var color = '';
  var count = 1000 * 10;

  (function dispatch() {
    if (!--count) return; //递归停止条件
    setTimeout(function (){//使用setTimout隔开连续的脚本执行，给UI线程操作空间
      color=getRandomColor();
      div.style.backgroundColor=color;
      dispatch();//递归调用

    })
  })();

  //随机产生颜色
  function getRandomColor() {
    var letters = '0123456789ABCEDF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
  }

  /*for (var i = 0; i < 1000 * 10; i++) {
    color = getRandomColor();
    console.log(`index:${i + 1}---------------`, color);//打印出颜色，确认随机颜色确实产生了
    div.style.background = color;
  }*/

</script>
</body>
</html>
